package com.sunrise.estoque.repositorio;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sunrise.estoque.repositorio.iface.SetorDao;
import com.sunrise.generico.acesso.DaoService;
import com.sunrise.generico.entidade.Setor;
import com.sunrise.generico.visao.Filtro;

@Repository
public class SetorDaoImpl extends DaoService<Setor> implements SetorDao {

	public List<Setor> listarOrdenado() {
		List<Setor> list = listar(Setor.class);
		Collections.sort(list, new Comparator<Setor>() {

			@Override
			public int compare(Setor o1, Setor o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public List<Setor> search(Setor ex) {
		List<Setor> list =  searchByExample(Setor.class, ex);
		Collections.sort(list, new Comparator<Setor>() {

			@Override
			public int compare(Setor o1, Setor o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public Setor getById(Long id) {
		return getById(id, Setor.class);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Setor> listarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(Setor.class);
		crit.add(Restrictions.ilike("nome", nome, MatchMode.ANYWHERE));
		return crit.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Setor> buscarPorFiltros(Filtro setor) {
		Criteria crit = getSession().createCriteria(Setor.class);
		if (setor.getNome() != null) {
			crit.add(Restrictions.ilike("nome", setor.getNome(),
					MatchMode.ANYWHERE));
		}

		if (setor.getAtivo() != null) {
			crit.add(Restrictions.eq("ativo", setor.getAtivo().getCodigo()));
		}
		
		crit.addOrder(Order.asc("nome"));
		return crit.list();
	}
	
	@Override
	public Setor buscarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(Setor.class);
		crit.add(Restrictions.eq("nome", nome).ignoreCase());
		return (Setor) crit.uniqueResult();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Setor> buscarSetorPorNome(String[] nomes) {
		Criteria crit = getSession().createCriteria(Setor.class);
		Disjunction or = Restrictions.disjunction();
		crit.add(or);
		for(String nome : nomes){
			or.add(Restrictions.eq("nome", nome).ignoreCase());
		}
		return crit.list();
	}

}
